import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName LC18
 * @Author ykx
 * @Date 2024/3/5 16:25
 * @Version 1.0
 */
public class LC18 {

    public static void main(String[] args) {
        LC18 lc18 = new LC18();
        int target = -1000000000;
        int[] nums = {0, 0, 0, -1000000000, -1000000000, -1000000000, -1000000000};

        System.out.println(lc18.fourSum(nums, target));
    }

    public List<List<Integer>> fourSum(int[] nums, int target) {
        // 结果
        List<List<Integer>> result = new ArrayList<>();

        if (nums.length < 4) {
            return result;
        }


        // 先对数组排序
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    // 和太小，左指针又移动
                    if ((long) (nums[i] + nums[j] + nums[left] + nums[right]) < target) {
                        left++;
                    } else if ((long) (nums[i] + nums[j] + nums[left] + nums[right]) > target) {
                        right--;
                    } else {
                        // 结果中每个元素集合
                        List<Integer> integers = new ArrayList<>();
                        integers.add(nums[i]);
                        integers.add(nums[j]);
                        integers.add(nums[left]);
                        integers.add(nums[right]);
                        result.add(integers);
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    }
                }
            }
        }

        return result;
    }
}
